package com.luxiu.extensionlib.imageView

import android.content.Context
import android.graphics.drawable.Drawable
import android.graphics.drawable.StateListDrawable
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import com.luxiu.extensionlib.R

class VariousImageView(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
    AppCompatImageView(context, attrs, defStyleAttr) {

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    private var mNormalDrawable: Drawable?

    private var mPressedDrawable: Drawable?

    private var mUnableDrawable: Drawable?


    private val states = arrayOfNulls<IntArray>(4)

    private var mStateBackground: StateListDrawable = background as? StateListDrawable ?: StateListDrawable()

    init {
        states[0] = intArrayOf(android.R.attr.state_pressed, android.R.attr.state_enabled)
        states[1] = intArrayOf(android.R.attr.state_enabled, android.R.attr.state_focused)
        states[3] = intArrayOf(-android.R.attr.state_enabled)
        states[2] = intArrayOf(android.R.attr.state_enabled)


        val a = getContext().obtainStyledAttributes(attrs, R.styleable.VariousImageView)
        try {
            mNormalDrawable = a.getDrawable(R.styleable.VariousImageView_mNormalBackgroundColor)
            mPressedDrawable = a.getDrawable(R.styleable.VariousImageView_mPressedBackgroundColor)
            mUnableDrawable = a.getDrawable(R.styleable.VariousImageView_mUnableBackgroundColor)
            setStateBackground(mNormalDrawable, mPressedDrawable, mUnableDrawable)
            setAnimationDuration(a.getInteger(R.styleable.VariousImageView_mAnimationDuration, 0))
        } finally {
            a.recycle()
        }
    }

    /**
     * 设置不同状态下的背景
     */
    fun setStateBackground(normal: Drawable?, pressed: Drawable?, unable: Drawable?) {
        this.mNormalDrawable = normal
        this.mPressedDrawable = pressed
        this.mUnableDrawable = unable

        //set background
        mPressedDrawable?.let {
            mStateBackground.addState(states[0], mPressedDrawable)
            mStateBackground.addState(states[1], mPressedDrawable)
        }

        mUnableDrawable?.let {
            mStateBackground.addState(states[3], mUnableDrawable)
        }

        mNormalDrawable?.let {
            mStateBackground.addState(states[2], mNormalDrawable)
        }
        setBackgroundDrawable(mStateBackground)
    }

    /**
     * 设置动画时长
     */
    fun setAnimationDuration(duration: Int) {
        mStateBackground.setEnterFadeDuration(duration)
        mStateBackground.setExitFadeDuration(duration)
    }
}